﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;

using HadronData;

namespace Hadron.Entities
{
    abstract class LandEntity
        : Entity
    {
        protected Layer m_layerAnchor;
        protected Edge m_edgeAnchor;
        protected Transformation m_trnLayerPlacement;

        public LandEntity(EntityMarker p_entityMarker, Environment p_environment)
            : base(p_entityMarker, p_environment)
        {
            FindAnchor();
        }

        public void FindAnchor()
        {
            Level level = m_environment.CurrentLevel;
            HadronData.Ray ray = new HadronData.Ray(Vector2.Zero, Vector2.UnitY);
            ray.Transform(m_trnPlacement);
            Vector2 vecIntersectionPoint = Vector2.Zero;
            if (!level.Intersects(ray, ref vecIntersectionPoint))
                return;

            List<PickedEdge> listPickedEdges = level.PickEdges(vecIntersectionPoint);
            PickedEdge pickedEdge = listPickedEdges[0];
            m_edgeAnchor = pickedEdge.LocalEdge;
            m_layerAnchor = pickedEdge.Layer;

            Position = vecIntersectionPoint;
            m_trnPlacement.RotationDirection = pickedEdge.Edge.Direction;
            m_trnLayerPlacement = m_layerAnchor.Placement.Inverse.ComposeWith(m_trnPlacement);
        }

        public void SnapToAnchor()
        {
            if (m_layerAnchor != null)
                m_trnPlacement = m_layerAnchor.Placement.ComposeWith(m_trnLayerPlacement);
        }

        public override void Update(GameTime p_gameTime)
        {
            SnapToAnchor();
            m_circleBounds.Centre = m_trnPlacement.Translation;
        }
    }
}
